//
// Created by yun on 2020/8/4.
//

#include "udpserver.h"
#include <QDataStream>
#include <QUdpSocket>
#include <stdlib.h>
#include <QDebug>

MyudpServer::MyudpServer(QObject *parent, int port): QObject(parent)
{
    m_udpSocket = new QUdpSocket(this);
    connect(m_udpSocket, SIGNAL(readyRead()), this, SLOT(slotRead()));
    ip = QHostAddress("127.0.0.1");
    this->port = port;
    bool result = m_udpSocket->bind(ip, port);
    if(!result)     //udpsocket进行绑定和server一样的端口
    {
        qDebug() << " bind port " << port << " fail";
//        QMessageBox::information(this,"error","bind fail"); //绑定失败弹出信息对话框
    }
}

MyudpServer::~MyudpServer()
{

}

//出现一个新连接时调用
void MyudpServer::slotRead()
{
    while(m_udpSocket->hasPendingDatagrams())
    {
        int n = m_udpSocket->pendingDatagramSize();
        char *buf = new char[n];
        m_udpSocket->readDatagram(buf, n);   //读取数据
        unpackData(buf, n);   //解包
        delete []buf;
    }
}


//解包之后的处理
void MyudpServer::recv(char *data)
{
    printf("%s\n", data);
}
